package com.inst.jsoup_html_demo.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.inst.jsoup_html_demo.R;
import com.inst.jsoup_html_demo.bean.HomeTab;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;

/**
 * Created by Administrator on 2018/1/24 0024.
 */

public class HomeAdapter  extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> implements View.OnClickListener{
    private ArrayList<HomeTab> datas;
    public HomeAdapter(ArrayList<HomeTab> arrayList) {
        this.datas = arrayList;
    }
    private HomeAdapter.OnItemClickListener mOnItemClickListener = null;

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    //define interface
    public static interface OnItemClickListener {
        void onItemClick(View view , int position);
    }
    /**
     * Called when a view has been clicked.
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        if (mOnItemClickListener != null) {
            //注意这里使用getTag方法获取position
            Logger.e("监听","----------");
            mOnItemClickListener.onItemClick(v,(int)v.getTag());
        }
    }


    @Override
    public HomeAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_test1_item, parent, false);
        HomeAdapter.MyViewHolder holder = new HomeAdapter.MyViewHolder(view);
        view.setOnClickListener(this);
        return holder;
    }

    @Override
    public void onBindViewHolder(HomeAdapter.MyViewHolder holder, int position)
    {
        holder.tvTitle.setText(datas.get(position).getTitle());
        holder.tvurl.setText(datas.get(position).getImageUrl());
        //将position保存在itemView的Tag中，以便点击时进行获取
        holder.itemView.setTag(position);
    }

    @Override
    public int getItemCount()
    {
        return datas.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder
    {

        TextView tvTitle;
        TextView tvurl;

        public MyViewHolder(View view)
        {
            super(view);
            tvTitle = (TextView) view.findViewById(R.id.tv_title);
            tvurl = (TextView) view.findViewById(R.id.tv_url);
        }
    }
}
